package com.dyna.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyna.domain.entity.Items;
import com.dyna.domain.entity.LuckyBagEvent;
import com.dyna.domain.form.event.LuckyBagEventForm;
import com.dyna.enums.DeleteValueEnum;
import com.dyna.enums.LuckyBagEventStatusEnum;
import com.dyna.mapper.ItemsMapper;
import com.dyna.mapper.LuckyBagMapper;
import com.dyna.service.LuckyBagService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Service
public class LuckyBagServiceImpl extends ServiceImpl<LuckyBagMapper, LuckyBagEvent> implements LuckyBagService {

    private final ItemsMapper itemsMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(LuckyBagEventForm form) {
        // 1.发布福袋
        LuckyBagEvent luckyBag = BeanUtil.copyProperties(form, LuckyBagEvent.class);
        long eventId = IdUtil.getSnowflakeNextId();
        luckyBag.setEventId(eventId);
        // TODO 根据物品价值是否需要审核
        luckyBag.setStatus(LuckyBagEventStatusEnum.PASS.getStatus());
        luckyBag.setStartTime(LocalDateTime.now());
        // 目前默认福袋结束时间为1天
        luckyBag.setEndTime(LocalDateTime.now().plusDays(1));
        // 2.奖品明细
        List<LuckyBagEventForm.LuckyBagEventItem> eventPrizeList = form.getLuckyBagEventItemList();
        List<Long> itemIdsList = eventPrizeList.stream().map(LuckyBagEventForm.LuckyBagEventItem::getItemId).collect(Collectors.toList());
        LambdaQueryWrapper<Items> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Items::getItemId, itemIdsList);
        queryWrapper.eq(Items::getDelFlag, DeleteValueEnum.DELETE.getValue());
        List<Items> itemsList = itemsMapper.selectList(queryWrapper);
        List<String> coverImgList = itemsList.stream().limit(5).map(Items::getCoverImg).collect(Collectors.toList());
        luckyBag.setCoverUrl(coverImgList);
        // TODO 图片封面，获取前五个价值最高的物品的图片
        this.save(luckyBag);
        // 保存奖品明细
        this.doSaveLuckyBagEventItem(eventId, eventPrizeList);
        return Boolean.TRUE;
    }

    private void doSaveLuckyBagEventItem(long eventId, List<LuckyBagEventForm.LuckyBagEventItem> eventPrizeList) {

    }

}
